<template>
  <div>
    <!-- 用户明细表 -->
    <div class="ml-2 flex-1">
      <div>
        <a-card :bordered="false" style="height: 830px; width: 1380px">
          <a-form
            :model="searchForm"
            layout="inline"
            class="mt-3"
            ref="searchFormRef"
          >
            <a-form-item label="导出范围" name="villageNode">
              <a-radio-group v-model:value="searchForm.villageNode">
                <a-radio value="按小区导出">按小区导出</a-radio>
                <a-radio value="按机构导出">按机构导出</a-radio>
              </a-radio-group>
            </a-form-item>
            <a-form-item label="归属机构" name="comId">
              <a-tree-select
                v-model:value="searchForm.comId"
                tree-node-filter-prop="label"
                style="width: 260px"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                :tree-data="comanyList"
                placeholder="请选择归属机构"
                @change="onComIdChange"
                allow-clear
              />
            </a-form-item>
            <a-form-item label="收费期" name="feeYear">
              <a-date-picker
                v-model:value="searchForm.feeYear"
                format="YYYY"
                valueFormat="YYYY"
                picker="year"
                allow-clear
              />
            </a-form-item>
            <a-form-item label="收费时间" name="feeTime">
              <a-range-picker
                v-model:value="searchForm.feeTime"
                format="YYYY-MM-DD"
                valueFormat="YYYY-MM-DD"
                allow-clear
              />
            </a-form-item>
            <a-form-item label="业务类型" name="refundStatus">
              <a-select
                v-model:value="searchForm.refundStatus"
                placeholder="请选择"
                style="width: 200px"
                allow-clear
              >
                <a-select-option value="供热">供热</a-select-option>
                <a-select-option value="制冷">制冷</a-select-option>
                <a-select-option value="供水">供水</a-select-option>
                <a-select-option value="光伏">光伏</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item>
              <a-button
                type="primary"
                class="mr-3"
                :icon="h(SearchOutlined)"
                @click="onSearch"
                >查询</a-button
              >
              <a-button
                type="primary"
                :icon="h(RedoOutlined)"
                class="mr-3"
                @click="onReset"
                >重置</a-button
              >
              <a-button
                type="primary"
                :icon="h(HistoryOutlined)"
                class="mr-3"
                @click="onHistory"
                >导出历史</a-button
              >
              <a-button
                type="primary"
                :icon="h(ReconciliationOutlined)"
                class="mr-3"
                @click="onExport"
                >导出信息</a-button
              >
            </a-form-item>
          </a-form>
          <a-table
            :columns="columns"
            :data-source="dataSource"
            bordered
            :pagination="pagination"
            class="mt-5"
            :row-class-name="
              (_record: any, index: number) =>
                index % 2 === 1 ? 'table-striped' : null
            "
            :scroll="{ x: 4500, y: 550 }"
          >
          </a-table>
        </a-card>
      </div>
    </div>
    <a-modal
      title="导出历史"
      :visible="showHistory"
      @cancel="onCancel"
      width="1400px"
    >
      <a-table
        :columns="historyColumns"
        :data-source="historyDataSource"
        bordered
        :pagination="historyPagination"
        class="mt-5"
        :row-class-name="
          (_record: any, index: number) =>
            index % 2 === 1 ? 'table-striped' : null
        "
      >
        <template #bodyCell="{ column, record, text }">
          <template v-if="column.dataIndex === 'states'">
            <a-tag :bordered="false" color="success" v-if="record.states == '0'"
              >完成</a-tag
            >
            <a-tag :bordered="false" color="error" v-else>失败</a-tag>
          </template>
          <template v-if="column.dataIndex === 'active'">
            <a-button type="link" @click="onDown(record)">下载</a-button>
          </template>
        </template>
      </a-table>
    </a-modal>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, h, onMounted } from 'vue';
import {
  SearchOutlined,
  RedoOutlined,
  HistoryOutlined,
  ReconciliationOutlined,
} from '@ant-design/icons-vue';
import {
  getChargeDailyExportApi,
  getReportExportHistoryApi,
} from '#/api/core/statistical';
import {
  getCompanyTree,
  houseReportPage,
  exportHeatExchangeStationReport,
  getReportExportHistoryPage,
  exportHouseReport,
} from '#/api/core/DataTable';
import dayjs from 'dayjs';
import { message } from 'ant-design-vue';
const props = defineProps({
  selectedNodeId: {
    type: Array,
    default: [],
  },
});

// 表单数据
const searchFormRef = ref(null);
onMounted(() => {
  getTableData();
});
// 归属机构下拉
const comanyList = ref([]);
// 归属机构下拉请求数据
const getTableData = () => {
  getCompanyTree().then((res: any) => {
    console.log(res);
    // 递归处理树形数据，保持层级结构
    const processTreeData = (tree: any[]): any[] => {
      console.log(tree);
      return tree.map((item: any) => {
        const processedItem = {
          label: item.name,
          value: `${item.level}-${item.id}`,
          isLeaf: item.children && item.children.length > 0 ? false : true,
          children: [],
        };

        // 如果存在children，递归处理子节点
        if (item.children && item.children.length > 0) {
          processedItem.children = processTreeData(item.children);
        }

        return processedItem;
      });
    };

    const treeData = processTreeData([res.data]);
    console.log(treeData, '------------');
    comanyList.value = treeData;
  });
};
const onComIdChange = (value: string) => {
  console.log('选中的节点ID:', value);
  // 在这里可以根据选中的节点ID执行相应的操作
};

// 表单搜索
const searchForm = reactive({
  comId: '', // 归属机构
  feeYear: '', //收费期
  refundStatus: '', // 业务类型
  feeTime: '', // 缴费时间
  villageNode: '按小区导出', // 导出类型

  time: '',
  feeData: '',
  grState: '',
  operator: '',
  holder: [],
});
// 默认表格
const pagination = reactive({
  total: 0,
  pageSize: 10,
  current: 1,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, pageSize: number) => {
    pagination.current = page;
    pagination.pageSize = pageSize;
    onSearch();
  },
});
const dataSource = ref([]);
const columns = [
  {
    title: '子公司',
    dataIndex: 'comNameLevel5',
    key: 'comNameLevel5',
    align: 'center',
  },
  {
    title: '区域',
    dataIndex: 'comNameLevel4',
    key: 'comNameLevel4',
    align: 'center',
  },
  {
    title: '小区名称',
    dataIndex: 'village',
    key: 'village',
    align: 'center',
  },
  {
    title: '热力卡号',
    dataIndex: 'alipayConsNo',
    key: 'alipayConsNo',
    align: 'center',
  },
  {
    title: '住户名称',
    dataIndex: 'holder',
    key: 'holder',
    align: 'center',
  },
  {
    title: '入住状态',
    dataIndex: 'checkIn',
    key: 'checkIn',
    align: 'center',
  },
  {
    title: '建筑面积',
    dataIndex: 'buildingArea',
    key: 'buildingArea',
    align: 'center',
  },
  {
    title: '实供面积',
    dataIndex: 'actualSuppliedArea',
    key: 'actualSuppliedArea',
    align: 'center',
  },
  {
    title: '收费面积',
    dataIndex: 'feeArea',
    key: 'feeArea',
    align: 'center',
  },
  {
    title: '应收全费面积',
    dataIndex: 'receivableTotalArea',
    key: 'receivableTotalArea',
    align: 'center',
  },
  {
    title: '应收基本费面积',
    dataIndex: 'receivableBasicArea',
    key: 'receivableBasicArea',
    align: 'center',
  },
  {
    title: '用电性质',
    dataIndex: 'electricType',
    key: 'electricType',
    align: 'center',
  },
  {
    title: '用电单价（元/度）',
    dataIndex: 'electricPrice',
    key: 'electricPrice',
    align: 'center',
  },
  {
    title: '用水性质',
    dataIndex: 'waterType',
    key: 'waterType',
    align: 'center',
  },
  {
    title: '用水单价（元/m³）',
    dataIndex: 'waterPrice',
    key: 'waterPrice',
    align: 'center',
  },
  {
    title: '用气性质',
    dataIndex: 'gasType',
    key: 'gasType',
    align: 'center',
  },
  {
    title: '用气单价（元/m³）',
    dataIndex: 'gasPrice',
    key: 'gasPrice',
    align: 'center',
  },
  {
    title: '投产日期',
    dataIndex: 'createdTime',
    key: 'createdTime',
    align: 'center',
  },
  // {
  //   title: '实收全费面积',
  //   dataIndex: '',
  //   key: '',
  //   align: 'center',
  // },
];
// 默认表格查询
const onSearch = () => {
  if (!props.selectedNodeId || props.selectedNodeId.length === 0) {
    message.error('请选择左侧树结构！');
    return;
  } else {
    const query = {
      page: pagination.current,
      limit: pagination.pageSize,
      villageNode: props.selectedNodeId.join(','),
      // 公司节点ID
      companyNode: searchForm.comId ?? '',
      // 业务类型
      businessType:
        searchForm.refundStatus === undefined ? '' : searchForm.refundStatus,
      feeYear: searchForm.feeYear ? dayjs().format('YYYY') : '',
      // 收费时间
      chargingTime: searchForm.time
        ? `${dayjs(searchForm.time[0]).format('YYYY-MM-DD')},${dayjs(
            searchForm.time[1],
          ).format('YYYY-MM-DD')}`
        : '',
      // // 归属机构
      // heatExchangeStationNode:
      //   searchForm.comId === undefined ? '' : searchForm.comId,
    };
    houseReportPage(query).then((res: any) => {
      console.log('日报表', res.data);
      if (res.data.data) {
        dataSource.value = res.data.data;
        pagination.total = res.data.count;
      } else {
        message.error(res.data.msg || '数据获取失败');
      }
    });
  }
};
const onExport = () => {
  if (!props.selectedNodeId || props.selectedNodeId.length === 0) {
    message.error('请选择左侧树结构！');
    return;
  } else {
    if (searchForm.villageNode == '按小区导出') {
      const query = {
        villageNode: props.selectedNodeId.join(','),
        // 业务类型
        businessType: searchForm.refundStatus ?? '',
        feeYear: searchForm.feeYear ? dayjs().format('YYYY') : '',
        // 收费时间
        chargingTime: searchForm.time
          ? `${dayjs(searchForm.time[0]).format('YYYY-MM-DD')},${dayjs(
              searchForm.time[1],
            ).format('YYYY-MM-DD')}`
          : '',
      };
      exportHouseReport(query).then((res: any) => {
        console.log('导出信息', res);
        if (res.data.code === 200) {
          message.success('导出成功');
          // message.success(res.data.msg);
        } else {
          message.error('导出失败');
        }
      });
    } else {
      const query = {
        // 公司节点ID
        companyNode: searchForm.comId === undefined ? '' : searchForm.comId,
        // 业务类型
        businessType: searchForm.refundStatus ?? '',
        feeYear: searchForm.feeYear ? dayjs().format('YYYY') : '',
        // 收费时间
        chargingTime: searchForm.time
          ? `${dayjs(searchForm.time[0]).format('YYYY-MM-DD')},${dayjs(
              searchForm.time[1],
            ).format('YYYY-MM-DD')}`
          : '',
      };
      exportHouseReport(query).then((res: any) => {
        console.log('导出信息', res);
        if (res.data.code === 200) {
          message.success('导出成功');
          // message.success(res.data.msg);
        } else {
          message.error('导出失败');
        }
      });
    }
  }
};

// 导出历史
const historyPagination = reactive({
  total: 0,
  pageSize: 10,
  current: 1,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, pageSize: number) => {
    historyPagination.current = page;
    historyPagination.pageSize = pageSize;
    onHistory();
  },
});
const showHistory = ref(false);
const historyDataSource = ref([]);
const historyColumns = [
  {
    title: '文件名',
    dataIndex: 'fileName',
    key: 'fileName',
    align: 'center',
  },
  {
    title: '操作日期',
    dataIndex: 'operationDate',
    key: 'operationDate',
    align: 'center',
  },
  {
    title: '结束时间',
    dataIndex: 'endDate',
    key: 'endDate',
    align: 'center',
  },
  {
    title: '操作人',
    dataIndex: 'operatorName',
    key: 'operatorName',
    align: 'center',
  },
  {
    title: '机构',
    dataIndex: 'companyName',
    key: 'companyName',
    align: 'center',
  },
  {
    title: '状态',
    dataIndex: 'exportStatus',
    key: 'exportStatus',
    align: 'center',
  },
  {
    title: '操作',
    dataIndex: 'active',
    key: 'active',
    align: 'center',
  },
];
const onHistory = () => {
  showHistory.value = true;
  const query = {
    page: historyPagination.current,
    limit: historyPagination.pageSize,
    exportType: 22,
  };
  getReportExportHistoryPage(query).then((res: any) => {
    console.log('导出历史', res.data);
    if (res.data) {
      // 通过接口地址下载文件
      // window.open(res.data.data.data);
      historyDataSource.value = res.data.data;
      historyPagination.total = res.data.count;
    } else {
      message.error(res.data.msg || '数据获取失败');
    }
  });
};

const onCancel = () => {
  showHistory.value = false;
};
const onDown = (e: any) => {
  // console.log(e);
  const loading = message.loading({
    content: "下载中...",
    duration: 0,
  });

  try {
    // 下载地址拼接
    const url = e.urlAddress;

    // 使用a标签下载，避免X-Frame-Options错误
    const link = document.createElement("a");
    link.href = url;
    link.download = ""; // 触发下载而不是导航
    link.target = "_blank";
    link.style.display = "none";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    // 关闭loading
    setTimeout(() => {
      loading();
    }, 1000);
  } catch (error) {
    console.error("下载出错:", error);
    message.error("下载出错，请重试");
    loading();
  }
};
const onReset = () => {
  searchFormRef.value.resetFields();
};
</script>
<style scoped>
:deep(.ant-form-item) {
  margin-bottom: 10px !important;
}
</style>
